package mq;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: hujian
 * @Date: 2019/10/11 17:10
 * @Description: RabbitMq接收端
 */
public class Receive {

    private final static String QUEUE_NAME = "hello";
    private final static Logger log = LoggerFactory.getLogger(Receive.class);

    public static void main(String[] args) throws IOException, TimeoutException {
        /*这里怎么打开连接和信道，以及声明用于接收消息的队列，这些步骤与发送端基本上是一样的*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.96.156.197");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        /*确保这里的队列是存在的*/
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        log.info(" [*] Waiting for messages. To exit press CTRL+C");

        //创建队列消费者
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = "";
                try{
                    message = new String(body, "GBK");
                    log.info(">>> mq msg : {}", message);
                } catch (Exception e){
                    log.error(message, e);
                }
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
